package com.zahb.qadx.ui.activity.videopage;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.tencent.mars.xlog.Log;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.model.CommonData;
import com.zahb.qadx.model.MainFunc2;
import com.zahb.qadx.model.MicroVideoData;
import com.zahb.qadx.model.VideoListBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.Tips;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

//微视频滑动播放
public class FlipVideoActivity extends BaseActivity implements
        OnItemClickListener, MicroVideoPlayerFragment.onFullHalfViewClickListener {

    @BindView(R.id.view_pager2)
    ViewPager2 viewPager2;
    @BindView(R.id.container_layout)
    ConstraintLayout mContainerLayout;
    static CommonData<MicroVideoData.MicroVideoBean> microVideoBeans;
    static ArrayList<MainFunc2> mainFunc2s;
    //   String mSourceId,mName;
    MicroVideoData.MicroVideoBean mMicroVideoBean;
    private ConstraintSet mPortraitConstraintSet;
    private ConstraintSet mLandscapeConstraintSet;

    private View mDecorView;
    private int mDefaultOption;
    private int mNavigationBarColor;
    private boolean Home = false;
    private String mSourceId, mVideoid, name;
    private int value=0;//当前第几个视频
    private final TaskListFragmentAdapter mTaskListFragmentAdapter=new TaskListFragmentAdapter(this);
    private int mPage;//当前页面
    private int categoryId=-10;
    private boolean After=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#000000"));//
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_flip_video;
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            mTopBarContainer.setVisibility(View.VISIBLE);
            mTopBarDivider.setVisibility(View.GONE);
            mPortraitConstraintSet.applyTo(mContainerLayout);
            mDecorView.setSystemUiVisibility(mDefaultOption);
            getWindow().setNavigationBarColor(mNavigationBarColor);
            StatusBarCompat.setStatusBarColor(this, Color.parseColor("#000000"));
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTopBarContainer.setVisibility(View.GONE);
            mTopBarDivider.setVisibility(View.GONE);
            mLandscapeConstraintSet.applyTo(mContainerLayout);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            mDecorView.setSystemUiVisibility(option);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
            StatusBarCompat.setStatusBarColor(this, Color.parseColor("#000000"));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        Drawable drawable=getResources().getDrawable(R.drawable.ic_back_white2);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mTopBarStartText.setCompoundDrawables(drawable, null, null, null);
        if (getIntent().getStringExtra("SourceId") != null) {
            Home = true;
            mSourceId = getIntent().getStringExtra("SourceId");
            getVideoId(mSourceId);
        }
        microVideoBeans = (CommonData<MicroVideoData.MicroVideoBean>) getIntent().getSerializableExtra("bean");//上个页面给的集合
        mMicroVideoBean = (MicroVideoData.MicroVideoBean) getIntent().getSerializableExtra("mTaskAdapter");
        value=  getIntent().getExtras().getInt("value");//当前第几个视频
        mainFunc2s = (ArrayList<MainFunc2>) getIntent().getSerializableExtra("HomeVideoData");
        mTopBarContainer.setBackgroundColor(Color.parseColor("#000000"));
        viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        viewPager2.setOffscreenPageLimit(1);
        //判断从哪里来
        if (Home) {
        } else {
            categoryId=getIntent().getExtras().getInt("categoryId");
            mPage=getIntent().getExtras().getInt("mPage");
            viewPager2.setAdapter(mTaskListFragmentAdapter);
        }
        initRecyclerView();
        initConstraintSets();
        mDecorView = getWindow().getDecorView();
        mDefaultOption = mDecorView.getSystemUiVisibility();
        mNavigationBarColor = getWindow().getNavigationBarColor();
        viewPager2.setCurrentItem(value,false);//调到指定页面
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (positionOffset==0){
                    Log.d("当前页面我是",viewPager2.getCurrentItem()+"");
                    if (microVideoBeans!=null){
                        // TODO: 2021/7/8  上拉加载暂时去掉
//                        if (microVideoBeans.getList().size()<viewPager2.getCurrentItem()+3&&After&&Home==false && categoryId !=-10){
//                            getTaskList();
//                        }

                    }

                }

            }
        });

    }

    @Override
    public void onBackPressed() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            super.onBackPressed();
        }
    }

    private void initRecyclerView() {

        final int divider_h = DisplayUtil.dip2px2(5.5f);
        final int divider_v = DisplayUtil.dip2px(16.5f);
        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                outRect.set(0, 0, 0, 0);
                if (parent.getChildAdapterPosition(view) % 2 == 0) {// 左边
                    outRect.right = divider_h;
                } else if (parent.getChildAdapterPosition(view) % 2 == 1) {// 右边
                    outRect.left = divider_h;
                }
                if (parent.getChildAdapterPosition(view) >= 2) {
                    outRect.top = divider_v;
                }
            }
        };

    }

    private void initConstraintSets() {
        mPortraitConstraintSet = new ConstraintSet();
        mPortraitConstraintSet.clone(mContainerLayout);
        mLandscapeConstraintSet = new ConstraintSet();
        mLandscapeConstraintSet.clone(mContainerLayout);
        mLandscapeConstraintSet.clear(R.id.view_pager2);
        mLandscapeConstraintSet.connect(R.id.view_pager2, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
        mLandscapeConstraintSet.connect(R.id.view_pager2, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
        mLandscapeConstraintSet.connect(R.id.view_pager2, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);
        mLandscapeConstraintSet.connect(R.id.view_pager2, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.empty;
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

    }

    @Override
    public void onRequestFull(ImageView view) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    public void onRequestHalf(ImageView view) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }


    private class TaskListFragmentAdapter extends FragmentStateAdapter {


        private SparseArray<MicroVideoPlayerFragment> mSparseArray = new SparseArray<>();


        TaskListFragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            boolean isAudio = false;
            if (Home) {
                MicroVideoPlayerFragment fragment =
                        mSparseArray.get(position, MicroVideoPlayerFragment.newInstancess(mVideoid, isAudio, position,name));
                mSparseArray.put(position, fragment);
//                mSparseArray.get(position).setOnFullHalfViewClickListener(FlipVideoActivity.this);
            } else {
                if (mSparseArray.get(position)==null){
                    if (microVideoBeans != null) {
                        MicroVideoPlayerFragment fragment =
                                mSparseArray.get(position, MicroVideoPlayerFragment.newInstancess(microVideoBeans.getList().get(value).getSourceId(), isAudio, position,microVideoBeans.getList().get(value).getName()));
                        mSparseArray.put(position, fragment);
                        Log.d("数据1",fragment.getTag()+"---"+ position);
//                        mSparseArray.get(position).setOnFullHalfViewClickListener(FlipVideoActivity.this);
                    }
                }

            }
            Log.d("数据",mSparseArray.size()+"---"+ position);
            return mSparseArray.get(position);
        }



        @Override
        public int getItemCount() {
//            return    microVideoBeans==null?1:microVideoBeans.getList().size();
            return    1;
        }


    }

    private void getVideoId(String materialId) {
        addDisposable(RetrofitService.getNetService().postMaterialInfo(materialId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        mVideoid = response.getData().getSourceId();
                        name = response.getData().getName();
                        viewPager2.setAdapter(mTaskListFragmentAdapter);

                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }


    private void getTaskList() {
        After=false;
        mPage++;
        Map<String, Object> params = new HashMap<>();
        params.put("categoryId",categoryId );
        Log.d("categoryId",categoryId+"");
        params.put("pageNum",mPage );
        params.put("pageSize",10 );
        Gson mGson = new Gson();
        String json = mGson.toJson(params);
        android.util.Log.e("json",json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        addDisposable(RetrofitService.getNetService()
                .getStudentsGetAListOfMicroVideos(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        if (response.getData() .getList().size()!= 0) {
                            After=true;
                            if (mPage == 1) {
                                microVideoBeans = response.getData();
                            } else {
                                microVideoBeans.getList().addAll(response.getData().getList());
                                mTaskListFragmentAdapter.notifyDataSetChanged();
                            }
                        }else {
                            After=false;
//                            showBindToast("已经到底了");
                        }
                    } else {
                        showBindToast(response.getErrorInfo());
                    }

                }, throwable -> {
                    throwable.printStackTrace();

                    Tips.RequestError(getActivity());

                }));

    }
}
